package com.lan.springbootdruid.datasource;

import com.lan.springbootdruid.enums.DataSourceKey;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author: Lan
 * @date: 2019/5/5 18:22
 * @description:数据源切面
 */
@Aspect
@Order(-1)
@Component
@Slf4j
public class DynamicDataSourceAspect {

//    @Pointcut("execution(* com.lan.springbootdruid.controller..*.*(..))")
//    public void pointCut() {
//
//    }

    @Pointcut("@annotation(TargetDataSource)")
    public void pointCut() {

    }

    /**
     * 执行前更换数据源
     *
     * @param joinPoint
     */
    @Before("@annotation(TargetDataSource)")
    public void doBefore(JoinPoint joinPoint) {
        log.info("执行前");
        //获取类上的注解
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        TargetDataSource targetDataSource = method.getAnnotation(TargetDataSource.class);
        if (targetDataSource == null) {
            log.info("使用默认数据源：{}", DataSourceKey.DB_MASTER);
            DynamicDataSourceContextHolder.set(DataSourceKey.DB_MASTER);
        } else {
            log.info("设置数据源：{}", targetDataSource.dataSourceKey());
            DynamicDataSourceContextHolder.set(targetDataSource.dataSourceKey());
        }
    }

    /**
     * 执行后清除数据源
     *
     * @param joinPoint
     */
    @After("@annotation(TargetDataSource)")
    public void doAfter(JoinPoint joinPoint) {
        log.info("执行后");
        //获取类上的注解
        TargetDataSource targetDataSource = joinPoint.getTarget().getClass().getAnnotation(TargetDataSource.class);
        if (targetDataSource == null) {
            log.info("当前数据源：{}", DataSourceKey.DB_MASTER);
        } else {
            log.info("当前数据源：{}", targetDataSource.dataSourceKey());
        }
        DynamicDataSourceContextHolder.clear();
    }
}
